<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    let o = {
      name: 'tom'
    }

    function fn() {
      console.log(this)  //window
    }

    fn()  //此时什么都不加，this指向的是windows

    let o2 = {
      name: 'tom'
    }

    function fn2() {
      console.log(this) //{name: 'tom'}
    }
    // 使用call方法之后，会改变this的指向
    fn2.call(o2)

    let o3 = {
      name: 'tom'
    }

    function fn3(a, b) {
      console.log(this) // {name: 'tom'}
      console.log(a + b); // 3
    }
    // 使用call方法之后，会改变this的指向
    fn3.call(o3, 1, 2)

    // call方法
    function Student(theName, theAge) {
      this.name = theName;
      this.age = theAge
    }
    var stu = { className: "114期" }
    Student.call(stu, '小明', 19)
    console.log(stu); // {className: "114期", name: "小明", age: 19}


    // 借助call实现了继承
    function Father(name, age, sex) {
      this.name = name
      this.age = age
      this.sex = sex
    }
    function Son(name, age, sex) {
      // 这里使用son中的this，替换father中的this
      Father.call(this, name, age, sex)
    }

    let son = new Son('tom', 18, '男')
    console.log(son);

    function Son2(name, age, sex, hobby) {
      // 这里使用son中的this，替换father中的this
      Father.call(this, name, age, sex)
      this.hobby = hobby
    }

    let son2 = new Son2('tom', 18, '男', '打篮球')
    console.log(son2);




    var Pet = {
      words: '...',
      speak: function (say) {
        console.log(say + '' + this.words)
      }
    }
    Pet.speak('Speak'); // 结果：Speak...

    var Dog = {
      words: 'Wang'
    }
    //将this的指向改变成了Dog
    Pet.speak.call(Dog, 'Speak'); //结果： SpeakWang
  </script>
</body>

</html>